//
//  EmoticonManager.swift
//  EmoticonKeyBoard
//
//  Created by apple on 15/11/20.
//  Copyright © 2015年 apple. All rights reserved.
//

import UIKit

//主要负责加载组织所有表情文件 工具类 
class EmoticonManager: NSObject {
    
    //使用单例 避免每次通过磁盘读取文件
    static let emoticonManager: EmoticonManager = EmoticonManager()
    
    lazy var packages = [EmoticonPackage]()
    
    override init() {
        super.init()
        loadPackages()
    }
    
    
    func textToImageText(str: String, font: UIFont) -> NSAttributedString {
        ///1.在[奥特曼]她说[爱你]字符串中 找到对应的表情字符串
        //1.1  匹配方案
        // []  是正则表达式中的特殊字符  需要转译
        let pattern = "\\[.*?\\]"
        
        //实例化正则
        let regex = try! NSRegularExpression(pattern: pattern, options: [])
        
        let result = regex.matchesInString(str, options: [], range: NSMakeRange(0, str.characters.count))
        
        print(result)
        // 2.在表情的对象数组中 通过找到的表情字符串 找到对应的表情对象
        let strM = NSMutableAttributedString(string: str)
        //倒序遍历结果
        var count = result.count - 1
        while count >= 0 {
            //将每一个结果中的range 获取到
            let range = result[count].rangeAtIndex(0)
            //截取对应的字符串
            let subStr = (str as NSString).substringWithRange(range)
            print(subStr)
            
            //获取对应的表情模型
            if let emoticon = getEmoticon(subStr) {
                
                // 3.再根据 表情对象中的imagePath找到对应的图片
                let imageText = EmoticonAttachment().emoticonimageText(emoticon,font: font)
                
                //替换属性文本
                strM.replaceCharactersInRange(range, withAttributedString: imageText)
            }
            //将表情对象中的imagePath对应的图片 转换成 属性文本
            
            count--
        }
        
        return strM
    }
    
    // 2.在表情的对象数组中 通过找到的表情字符串 找到对应的表情对象
    func getEmoticon(string: String) -> Emoticon? {
        
        //遍历所有的分组表情
        for p in EmoticonManager().packages {
            //filter 数组过滤器
            let list = p.emoticonList.filter({ (em) -> Bool in
                
                //如果元素的chs  和 传入的字符串相同就满足条件
                return em.chs == string
            })
            
            if let e = list.last {
                return e
            }
        }
        return nil
    }
    
    //加载分组表情
    func loadPackages() {
        //获取分组路径
        let path = NSBundle.mainBundle().pathForResource("emoticons", ofType: "plist", inDirectory: "Emoticons.bundle")
        
        //将plist文件 转换成字典
        let dict = NSDictionary(contentsOfFile: path!)!
        if let array = dict["packages"] as? [[String : AnyObject]] {
            for item in array {
                let id = item["id"] as! String
                //加载分组表情
                loadGroupPackage(id)
            }
        }
    }
    
    private func loadGroupPackage(id: String) {
        //获取每个分组中的Info.plist
        print(id)
        let path = NSBundle.mainBundle().pathForResource("Info", ofType: "plist", inDirectory: "Emoticons.bundle/\(id)")
        let dict = NSDictionary(contentsOfFile: path!)!
        //字典转模型
        let name = dict["group_name_cn"] as! String
        let array = dict["emoticons"] as! [[String : String]]
        let p = EmoticonPackage(id: id, name: name, emoticons: array)
        //向数组中添加表情分组
        packages.append(p)
    }
}
